﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace 服务器
{
    class Program
    {
        static void Main(string[] args)
        {
            //创建socket对象 new
            var socket=new Socket(
                AddressFamily.InterNetwork,
                SocketType.Stream, 
                ProtocolType.Tcp);

            //绑定ip与端口 bind
            socket.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"),11818));
            Console.WriteLine("服务已启动");
            //开始监听
            socket.Listen(20);
            Console.WriteLine("开始监听");

            //接受客户端请求accept,可以获取客户端对象
            Thread tclienThread=new Thread((s) =>
            {
                //因为客户端可能会有多个,所以循环
                while (true)
                {
                    Socket server = s as Socket;
                    Socket tclinet = server.Accept();
                    Thread tRecive = new Thread((s2) =>
                    {
                        Socket c1 = s2 as Socket;
                        byte[] bs = new byte[1024];
                        int len = 0;
                       while ((len = c1.Receive(bs)) > 0)
                            {
                                Console.WriteLine(Encoding.UTF8.GetString(bs, 0, len));

                            }
                     

                    });
                    tRecive.IsBackground = true;
                    tRecive.Start(tclinet);
                    Thread tsend=new Thread((s3) =>
                    {
                        Socket ssend = s3 as Socket;
                        ssend.Send(Encoding.UTF8.GetBytes(Console.ReadLine()));

                    });
                    tsend.IsBackground = true;
                    tsend.Start(tclinet);
                }

                
            });
            
            tclienThread.IsBackground = true;
            tclienThread.Start(socket);
           // Socket sclient = socket.Accept();
           // Console.WriteLine("准备接收 ");
            
           // //接受客户端报文
           ////byte[] bs=new byte[1024];
           ////int len= sclient.Receive(bs);
           // Console.WriteLine("接收到来自的消息"+sclient.RemoteEndPoint);
          
           //Console.WriteLine(Encoding.UTF8.GetString(bs,0,len));

           // sclient.Send(Encoding.UTF8.GetBytes(
           //     Console.ReadLine()));
           // Console.WriteLine("我又发送了一条信息");
            Console.ReadKey();


        }
    }
}
